package com.jiajunsong.blog.controller;


import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.jiajunsong.blog.domain.ImageCode;
import com.jiajunsong.blog.domain.Result;
import com.jiajunsong.blog.domain.ValidateCode;
import com.jiajunsong.blog.validatecode.ImageCodeGenerator;

@RestController
public class ValidateCodeController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	public static final String IMAGE_CODE_IN_SESSION = "IMAGE_CODE_IN_SESSION";
	public static final String SMS_CODE_IN_SESSION = "SMS_CODE_IN_SESSION";
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

	@GetMapping("/code/image")
	public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ImageCodeGenerator imageCodeGenerator = new ImageCodeGenerator();
		ImageCode imageCode = imageCodeGenerator.generate();
		ValidateCode validateCode = new ValidateCode(imageCode.getCode(), imageCode.getExpireTime());
		sessionStrategy.setAttribute(new ServletWebRequest(request), IMAGE_CODE_IN_SESSION, validateCode);
		ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
	}

	@GetMapping("/code/sms")
	public Result createSmsCode(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletRequestBindingException {
		String code = RandomStringUtils.randomNumeric(6);
		ValidateCode validateCode = new ValidateCode(code, 60);
		sessionStrategy.setAttribute(new ServletWebRequest(request), SMS_CODE_IN_SESSION, validateCode);
		String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
		logger.info("向手机：" + mobile + "   发送验证码：" + code);
		return new Result("", "向手机" + mobile + "发送验证码成功");
	}

	@GetMapping("/getimagecodeinsession")
	public ValidateCode getimagecodeinsession(HttpServletRequest request) {
		ValidateCode imageCode = (ValidateCode) sessionStrategy.getAttribute(new ServletWebRequest(request),
				IMAGE_CODE_IN_SESSION);
		return imageCode;
	}
	
	@GetMapping("/getsmscodeinsession")
	public ValidateCode getsmscodeinsession(HttpServletRequest request) {
		ValidateCode smsCode = (ValidateCode) sessionStrategy.getAttribute(new ServletWebRequest(request),
				SMS_CODE_IN_SESSION);
		return smsCode;
	}
}
